import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;
    public TestHeap(){
        this.elem = new int[10];//对数组进行初始化
    }
    public void createHeap(int[] array){
        //将数组传给elem（此时是不需要算时间复杂度的）
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
        for (int i = (usedSize-1-1)/2; i >= 0 ; i--) {
            shiftDown(i,usedSize);
        }
    }
    //向下调整--实现大根堆(时间复杂度为O（n))
    public void shiftDown(int parent, int len){
        int child = 2*parent + 1;
        //是不是一定有左孩子
        while (child < len){
            //一定不会越界
            if (child + 1 < len && elem[child] < elem[child + 1]){
                child = child + 1;
            }
            //孩子大于父节点
            if (elem[parent] < elem[child]){
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                parent = child;
                child = 2*parent + 1;
            }else {
                break;
            }
        }
    }
    //堆的插入---向上调整
    public void push(int val){
        //将该元素插入到最后一个子节点处
        //判断elem数组是否已经满了
        if (isFull()){
            elem = Arrays.copyOf(elem, 2*elem.length);
        }
        //插入
        elem[usedSize] = val;
        usedSize++;
        shiftUp(usedSize - 1);
    }
    public boolean isFull(){
        return usedSize == elem.length;
    }
    //向上调整方法
    public void shiftUp(int child){
        int parent = (child - 1) / 2;
        while (parent >= 0){
            if (elem[parent] < elem[child]){
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                child = parent;
                parent = (child - 1) / 2;
            }else {
                break;
            }
        }
    }
    //删除元素
    //1.0小标和最后一个下标元素进行交换
    //2.向下调整0下标这棵树--变成大根堆或者小根堆
    //3.此时调整结束的位置有变化（因为删除了一个元素，usedSize会变化)
    public void poll(){
        if (isEmpty()){
            throw new HeapEmptyException("堆为空！");
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize - 1];
        elem[usedSize - 1] = tmp;
        usedSize--;
        shiftDown(0, usedSize);
    }
    public boolean isEmpty(){
        return usedSize == 0;
    }
}
